#! /usr/bin/bash

SourceDir="D:\bywg\debug_sites"
adb=/mnt/d/adb/adb.exe

#推送文件：如果文件是可执行站点则重启站点
function pushAndSync(){
	local file=$1
	local destDir=$2
	if [ $panelAddress != "local" ]; then
		local panelSelection="-s ${panelAddress}"
	fi

	#推送文件
	${adb} $panelSelection push ${SourceDir}\\${file} ${destDir}
	#修改执行权限
	${adb} $panelSelection shell chmod 0777 ${destDir}/${file}
	#显示新程序信息
	${adb} $panelSelection shell ls -l ${destDir}/${file}
	#同步内存
	${adb} $panelSelection shell sync
	
	#重启程序
	local outputLine=$(${adb} $panelSelection shell ps -ef | grep ${file})
	echo ${outputLine}
	local pid=$(echo ${outputLine} | cut -d ' ' -f 1)
	if [[ $pid =~ ^[0-9]+$ ]]
	then
		echo "adb $panelSelection shell kill -9 $pid"
		${adb} $panelSelection shell kill -9 $pid
	else
		echo "can not get effective pid ..."
	fi
}


#显示并构造支持推送的文件
function echoAndBuildPushArray(){
cat << _EOF_
-----------------------------
site:
	[1]:	query_site
	[2]: 	config_site
	[3]: 	ble_site
	[4]: 	synergy_site
	[5]: 	master_coordinate_site
-----------------------------
_EOF_

	pushArray[1]=query_site
	pushArray[2]=config_site
	pushArray[3]=ble_site
	pushArray[4]=synergy_site
	pushArray[5]=master_coordinate_site
}


# 拷贝站点
cp --update /home/lhy/smarthome/edge_rk3308/software/build/edge_midware/* /mnt/d/bywg/debug_sites/

# 列出当前已连接设备列表
${adb} devices

#选择操作终端，如果没有则建立新链接
read -p "plese input panel address: " panelAddress
if [[ $panelAddress =~ ^[0-9]+.[0-9]+.[0-9]+.[0-9]+[:]?[[:digit:]]* ]]; then
	${adb} connect ${panelAddress}
	while true
	do
		${adb} -s ${panelAddress} shell byjs2023
		result=$?
		if [[ $result != 0 ]]; then
			sleep 2
			echo "start to connect to $panelAddress again ..."
			continue
		else
			break
		fi
	done
	echo "connect to $panelAddress successfully ..."
elif [ $panelAddress == "local" ]; then
	echo "local host ...."
else
	echo "please input effective panel ip address or local"
	exit
fi

echoAndBuildPushArray

read -p "choose files to push: " -a array
for index in "${array[@]}"
do
	pushAndSync ${pushArray[${index}]} /data/changhong/edge_midware
done

